<template>
  <div class="menu-content data-detail">
    <div class="top">
      <p class="right-title" style="margin-bottom: 20px;">指标数据核对清单</p>
      <div style="display: flex;justify-content: space-between;">
        <div>总指标数：{{totalIndiNum}} &nbsp;&nbsp;&nbsp;&nbsp;正确指标数：{{correctIndiNum}} &nbsp;&nbsp;&nbsp;&nbsp;异常指标数：<span style="color:  #DF3838;">{{errorIndiNum}}</span></div>
        <div style="text-align: right;">
          <w-select v-model="procValue" placeholder="请选择" @change="procChange">
            <w-option v-for="item in procOptions" :key="item.id" :label="item.name" :value="item.name">
            </w-option>
          </w-select>
          <w-select v-model="indexValue" filterable placeholder="请选择" @change="indexChange">
            <w-option v-for="item in indexOptions" :key="item.id" :label="item.zbName" :value="item.zbName">
            </w-option>
          </w-select>
          <w-date-picker :picker-options="pickerOptions" format="yyyy 年 MM 月" value-format="yyyy-MM" v-model="dateValue"
            type="month" @change="dateChange"></w-date-picker>
          <!-- <w-button type="primary">下载模板</w-button> -->
          <w-button type="primary" @click="exportExcel">导出</w-button>
          <w-upload class="upload-demo" action="string" :file-list="fileListUpload" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :show-file-list="false" :http-request="uploadFile">
            <w-button type="primary">导入</w-button>
          </w-upload>
          <w-button type="primary" @click="moreCheck">{{allCheckInfo}}</w-button>
        </div>
      </div>
    </div>
    <div class="table">
      <w-table :max-height="tableHeight" border id="out-table" ref="multiTable" :data="tableData" style="width: 100%"
        @cell-click="editable" @select="selectFun" @select-all="handleSelectAll" @selection-change="handleSelectionChange">
        <w-table-column type="selection" width="50">
        </w-table-column>
        <w-table-column prop="period" label="统计周期">
          <template slot-scope="{row,$index}">
            <div>{{row.period?row.period:dateValue}}</div>
          </template>
        </w-table-column>
        <w-table-column prop="zbId" label="指标ID">
        </w-table-column>
        <w-table-column prop="zbName" label="指标名称">
        </w-table-column>
        <w-table-column prop="odrValue" label="ODR数据">
          <template slot-scope="{row,$index}">
            <!-- <div class="input-box" v-if="showODR[$index]">
              <w-input size="small" v-model="row.odrValue"></w-input>
            </div>
            <span v-if="!showODR[$index]">{{row.odrValue || row.odrValue==0 ?row.odrValue:'/'}}</span> -->
            <div>{{row.odrValue || row.odrValue=='0' ?row.odrValue:'/'}}</div>
          </template>
        </w-table-column>
        <w-table-column prop="hospitalValue" label="报表数据">
          <template slot-scope="{row,$index}">
            <div class="input-box" v-if="showHospitalValue[$index]">
              <w-input size="small" @change="changeValue(row)" v-model="row.hospitalValue"></w-input>
            </div>
            <span v-if="!showHospitalValue[$index]">{{row.hospitalValue || row.hospitalValue==0?row.hospitalValue:'/'}}</span>
            <!-- <div>{{row.hospitalValue || row.hospitalValue==0?row.hospitalValue:'/'}}</div> -->
          </template>
        </w-table-column>
        <w-table-column prop="diff" label="差值">
          <template slot-scope="{row,$index}">
            <div :style="{'color':row.isAbnormal==0?'#DF3838':row.isAbnormal==1?'#5DB730':'#000622'}">{{row.diff || row.diff=='0'?row.diff:'/'}}</div>
          </template>
        </w-table-column>
        <w-table-column prop="diffRate" label="差异率">
          <template slot-scope="{row,$index}">
            <div :style="{'color':row.isAbnormal==0?'#DF3838':row.isAbnormal==1?'#5DB730':'#000622'}">{{ row.diffRate || row.diffRate=='0' ? `${row.diffRate*100}%` : '/' }}</div>
          </template>
        </w-table-column>
        <w-table-column prop="hosValueSource" label="报表来源">
          <template slot-scope="{row,$index}">
            <div class="input-box" v-if="showHosValueSource[$index]">
              <w-input size="small" @change="changeValue(row)" v-model="row.hosValueSource"></w-input>
            </div>
            <span v-if="!showHosValueSource[$index]">{{row.hosValueSource?row.hosValueSource:'/'}}</span>
            <!-- <div>{{row.hosValueSource?row.hosValueSource:'/'}}</div> -->
          </template>
        </w-table-column>
        <w-table-column prop="operator" label="操作" width="150">
          <template slot-scope="{row,$index}">
            <a title="详情" class="detail" @click="openDrawer(row)"><i class="w-icon-list"></i></a>
            <w-button size="small" type="primary" @click="check(row,$index)">{{checkInfo[$index]}}</w-button>
          </template>
        </w-table-column>
      </w-table>
    </div>
    <w-drawer position="right" :visible.sync="visible" @onClose="handleClose">
      <div class="content-container bottom">
        <div class="left-table">
          <p class="right-title" style="margin-bottom: 20px;">数据处理步骤-环节口径调整</p>
          <w-table max-height="350" border :data="tableData1" @row-click="rowClick">
            <w-table-column prop="stepNo" label="步骤">
            </w-table-column>
            <w-table-column prop="sectionName" label="环节概述">
            </w-table-column>
            <w-table-column prop="handleTypeName" label="类型">
            </w-table-column>
            <w-table-column prop="conditionTypeName" label="条件">
            </w-table-column>
            <w-table-column prop="logicNo" label="序号">
            </w-table-column>
            <w-table-column prop="caliberNameMap" label="调整">
              <template slot-scope="{row,$index}">
                <!-- <span>{{row.caliberNameMap}}</span> -->
                <w-select v-model="caliber" placeholder="请选择" @change="caliberChange($event,row)">
                  <w-option v-for="item in row.caliberNameMap" :key="item.id" :label="item.name" :value="item.name">
                  </w-option>
                </w-select>
              </template>
            </w-table-column>
            <!-- <w-table-column prop="operator" label="操作">
              <template slot-scope="{row,$index}">
                <a v-if="!row.add" class="reduce" @click="reduce1(row)"><i class="w-icon-delete"></i></a>
                <a v-if="row.add" class="add" @click="add1($index)"><i class="w-icon-plus"></i></a>
              </template>
            </w-table-column> -->
          </w-table>
          <div class="button-wrap">
            <w-button size="large" type="primary" @click="goSql">SQL预览</w-button>
          </div>
        </div>
        <hr style="margin: 20px 0;" />
        <div>
          <!-- <w-input v-model="sqlContext" type="textarea"></w-input> -->
          <div id="wangeditor">
            <div ref="editorElem" style="text-align:left;"></div>
          </div>
          <div style="text-align: right;margin-top: 30px;">
            <w-button type="primary" @click="submitSql">提交</w-button>
          </div>
        </div>
      </div>
    </w-drawer>
  </div>
</template>
<script>
  import E from "wangeditor";
  import {
    getCurrentMonth,
    formatDate
  } from '@/utils/index.js'
  export default {
    components: {

    },
    data() {
      return {
        checkInfo: [],
        allCheckInfo: '核对',
        fileListUpload: [],
        showHospitalValue: [],
        showHosValueSource: [],
        procOptions: [],
        indexOptions: [],
        dateValue: '',
        tableData: [],
        tableData1: [],
        zbId: '',
        procId: '',
        indexValue: '',
        procValue: '',
        visible: false,
        rowZbId: '',
        rowAdd: '',
        caliberId: '',
        sqlContext: '',
        rowStepId: '',
        caliber: '',
        ids: '',
        editor: null,
        editorContent: '',
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6; //如果没有后面的-8.64e6就是不可以选择今天的
          }
        },
        tableHeight: document.documentElement.clientHeight - 250,
        isAllChoose: false,
        selection: [],
        totalIndiNum:'',//总指标数
        correctIndiNum:'',//正确指标数
        errorIndiNum:'',//异常指标数
      };
    },
    mounted() {
      this.editor = new E(this.$refs.editorElem);
      // 编辑器的事件，每次改变会获取其html内容
      this.editor.customConfig.onchange = html => {
        this.editorContent = html;
        // console.log(this.editorContent)
      };
      this.editor.customConfig.menus = [
        // 菜单配置
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'justify', // 对齐方式
        'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ];
      this.editor.create(); // 创建富文本实例
    },
    created() {
      // this.getData()
      this.getProcData()
      this.dateValue = getCurrentMonth()
      this.getTotal()
    },
    methods: {
      getTotal(){
        this.$Http
          .post("etlIndiDataCheckModel/findTotal")
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data
              this.totalIndiNum = content.totalIndiNum
              this.correctIndiNum = content.correctIndiNum
              this.errorIndiNum = content.errorIndiNum
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      selectFun(selection, row) {
        if (row.status == 1) {
          this.checkIndex(row, 0) //取消勾选
        } else {
          this.checkIndex(row, 1) //勾选
        }
      },
      handleSelectAll(val) {
        if (val.length > 0) {
          this.isAllChoose = true
        } else {
          this.isAllChoose = false
        }
        this.checkIndexs()
      },
      //勾选指标
      checkIndex(row, status) {
        // console.log('row', row)
        let param = {
          diff: row.diff || row.diff == 0 ? row.diff : '',
          diffRate: row.diffRate || row.diffRate == 0 ? row.diffRate : '',
          hosValueSource: row.hosValueSource ? row.hosValueSource : '',
          hospitalValue: row.hospitalValue ? row.hospitalValue : '',
          odrValue: row.odrValue ? row.odrValue : '',
          period: row.period ? row.period : '',
          zbId: row.zbId,
          zbName: row.zbName,
          status: status
        }
        this.$Http
          .post("etlIndiDataCheckModel/saveOrUpdate", param)
          .then(response => {
            if (response.data.response.code == "1") {
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //多个勾选指标
      checkIndexs() {
        var arr = []
        if (this.isAllChoose == true) {
          this.tableData.map((item, index) => {
            arr.push({
              diff: item.diff || item.diff == 0 ? item.diff : '',
              diffRate: item.diffRate || item.diffRate == 0 ? item.diffRate : '',
              hosValueSource: item.hosValueSource ? item.hosValueSource : '',
              hospitalValue: item.hospitalValue ? item.hospitalValue : '',
              odrValue: item.odrValue ? item.odrValue : '',
              period: item.period ? item.period : '',
              zbId: item.zbId,
              zbName: item.zbName,
              status: 1
            })
          })
        } else {
          this.tableData.map((item, index) => {
            arr.push({
              diff: item.diff || item.diff == 0 ? item.diff : '',
              diffRate: item.diffRate || item.diffRate == 0 ? item.diffRate : '',
              hosValueSource: item.hosValueSource ? item.hosValueSource : '',
              hospitalValue: item.hospitalValue ? item.hospitalValue : '',
              odrValue: item.odrValue ? item.odrValue : '',
              period: item.period ? item.period : '',
              zbId: item.zbId,
              zbName: item.zbName,
              status: 0
            })
          })
        }
        this.$Http
          .post("etlIndiDataCheckModel/saveOrUpdates", arr)
          .then(response => {
            if (response.data.response.code == "1") {
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //多选框选择事件
      handleSelectionChange(val) {
        this.selection = val
      },
      //多个校验
      moreCheck() {
        console.log('this.selection', this.selection)
        if (this.selection.length == 0) {
          this.$message.error('请至少勾选一个需要核对的指标~')
        } else {
          if (this.allCheckInfo.indexOf('中') == -1) {
            var arr = []
            var obj = {}
            this.allCheckInfo = '核对中...'
            this.selection.map((item, index) => {
              obj.zbId = item.zbId
              obj.procId = item.procId
              obj.startDate = this.dateValue + '-01 00:00:00'
              obj.endDate = this.dateValue + '-31 23:59:59'
              arr.push(obj)
              this.tableData.map((i, k) => {
                if (item.id == i.id) {
                  this.$set(this.checkInfo, k, '核对中...')
                }
              })
            })
            this.$Http
              .post("etlIndiDataCheckModel/checks", arr)
              .then(response => {
                this.allCheckInfo = '核对'
                this.selection.map((item, index) => {
                  this.tableData.map((i, k) => {
                    if (item.id == i.id) {
                      this.$set(this.checkInfo, k, '核对')
                    }
                  })
                })
                if (response.data.response.code == "1") {
                  this.$message.success('核对成功~')
                  this.getData()
                } else {
                  if (response.data.response.msg) {
                    this.$message.error(response.data.response.msg)
                  }
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        }
      },
      //单个核对
      check(row, index) {
        // if (!this.procId) {
        //   this.$message.error('请先选择存储过程~')
        // } else {
        if (this.checkInfo[index].indexOf('中') == -1) {
          this.$set(this.checkInfo, index, '核对中...')
          let param = {
            endDate: this.dateValue + '-31 23:59:59',
            procId: row.procId,
            startDate: this.dateValue + '-01 00:00:00',
            zbId: row.zbId
          }
          this.$Http
            .post("etlIndiDataCheckModel/check", param)
            .then(response => {
              this.$set(this.checkInfo, index, '核对')
              // this.checkInfo[index] = '核对'
              if (response.data.response.code == "1") {
                this.$message.success('核对成功~')
                this.getData()
              } else {
                this.$message.error(response.data.response.msg)
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
        // }
      },
      //点击步骤每一行
      rowClick(row) {
        this.editor.txt.html(row.sqlContext)
        this.sqlContext = row.sqlContext
        this.rowStepId = row.id
      },
      //提交SQL
      submitSql() {
        this.sqlContext = this.editor.txt.html()
        let param = {
          sqlContext: this.sqlContext,
          id: this.rowStepId
        }
        this.$Http
          .post("etlProdSecInfo/updateSql", param)
          .then(response => {
            if (response.data.response.code == "1") {
              this.$message.success('提交成功~')
              // this.getStep()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //跳转到SQL预览页面
      goSql() {
        this.$router.push({
          path: '/dataSql',
          query: {
            procId: this.procId,
            ids: this.ids
          }
        });
      },
      caliberChange(val, row) {
        row.caliberNameMap.map((item, index) => {
          if (item.name == val) {
            this.caliberId = item.id
            this.caliber = item.name
          }
        })
        this.getStep()
      },
      //获取步骤数据
      getStep() {
        if (!this.rowAdd) {
          let param = {
            procId: this.procId,
            zbId: this.rowZbId,
            id: this.caliberId
          }
          this.$Http
            .post("etlProdSecInfo/findSectionCaliberInfo", param)
            .then(response => {
              if (response.data.response.code == "1") {
                let content = response.data.response.data;
                this.tableData1 = content
                if (content.length > 0) {
                  this.sqlContext = content[0].sqlContext
                  this.editor.txt.html(content[0].sqlContext)
                  this.rowStepId = content[0].id
                  this.caliber = content[0].caliberName
                  var arr = []
                  content.map((item, index) => {
                    arr.push(item.id)
                  })
                  this.ids = arr.join(',')
                } else {
                  this.editor.txt.html('')
                }
              } else {
                if (response.data.response.msg) {
                  this.$message.error(response.data.response.msg)
                }
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      },
      //打开侧边抽屉
      openDrawer(row) {
        // if (!this.procId) {
        //   this.$message.error('请先选择存储过程~')
        // } else {
        this.visible = true
        this.rowZbId = row.zbId
        this.rowAdd = row.add
        this.procId = row.procId
        this.getStep()
        // }
        // this.getModelData()
        // this.getTypeData()
      },
      //关闭抽屉
      handleClose() {
        this.visible = false
      },
      //获取存储数据
      getProcData() {
        let param = {
          id: ''
        }
        this.$Http
          .post("etlProdInfo/findtableListInfo", param)
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              content.unshift({
                name: '全部',
                id: ''
              })
              this.procOptions = content
              this.procValue = content[0].name
              this.procId = content[0].id
              this.getIndexData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //获取指标数据
      getIndexData() {
        let param = {
          procId: this.procId
        }
        this.$Http
          .post("etlProdSecIndicInfo/findIndicatorInfo", param)
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              content.unshift({
                id: '',
                zbId: "",
                zbName: "全部"
              })
              this.indexOptions = content ? content : []
              this.indexValue = content[0] ? content[0].zbName : ''
              this.zbId = content[0] ? content[0].zbId : ''
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //日期切换事件
      dateChange(val) {
        this.dateValue = val
        this.updateTime()
      },
      updateTime() {
        this.$Http
          .get("etlIndiDataCheckModel/update/" + this.dateValue)
          .then(response => {
            if (response.data.response.code == "1") {
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //指标下拉框切换
      indexChange(val) {
        this.indexOptions.map((i, k) => {
          if (i.zbName == val) {
            this.zbId = i.zbId
          }
        })
        this.getData()
      },
      //存储过程下拉框切换
      procChange(val) {
        this.procOptions.map((i, k) => {
          if (i.name == val) {
            this.procId = i.id
          }
        })
        this.indexValue = ''
        this.zbId = ''
        this.getIndexData()
        // this.getData()
      },
      //获取核对清单
      getData() {
        this.$Http
          .post("etlIndiDataCheckModel/findList", {
            zbId: this.zbId,
            procId: this.procId,
            period: this.dateValue
          })
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              this.tableData = content

              if (this.tableData.length > 0) {
                this.tableData.map((item, index) => {
                  this.checkInfo.push('核对')
                })
                this.$nextTick(() => {
                  this.tableData.forEach(row => {
                    if (row.status == 1) {
                      this.$refs.multiTable.toggleRowSelection(row, true);
                    }
                  })
                })
              }

            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //上传excel到后端
      uploadFile(item) {
        const form = new FormData()
        form.append('file', item.file)

        this.$Http
          .post("etlIndiDataCheckModel/importExcel", form, {
            headers: {
              'Content-Type': 'multipart/form-data',
            }
          })
          .then(response => {
            console.log('导入', response.data)
            if (response.data.response.code == "1") {
              this.$message.success('导入成功~')
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      //定义导出Excel表格事件
      exportExcel() {
        let param = {
          zbId: this.zbId
        }
        // window.location.href="static/exportTemplate/a.xlsx"
        this.$Http
          .post("etlIndiDataCheckModel/export", param)
          .then(response => {
            if (response.data.response.code == "1") {
              let content = response.data.response.data;
              window.location.href = content.message
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
      // 初始化单元格显示状态
      setShowEditInit() {
        this.showHospitalValue.map((item, index) => {
          this.showHospitalValue[index] = false
        })
        this.showHosValueSource.map((item, index) => {
          this.showHosValueSource[index] = false
        })
      },
      //单击单元格事件
      editable(row, column, cell, event, index) {
        this.setShowEditInit()
        let nowObj = column.property
        var index = this.tableData.findIndex((item) => {
          return item.zbId === row.zbId
        })
        if (nowObj == 'hospitalValue') {
          this.showHospitalValue[index] = true
          this.$set(this.showHospitalValue, index, true)
        }
        if (nowObj == 'hosValueSource') {
          this.showHosValueSource[index] = true
          this.$set(this.showHosValueSource, index, true)
        }
      },
      changeValue(row) {
        this.editTableData(row)
      },
      //编辑报表数据
      editTableData(info) {
        let param = {
          "hospitalValue": info.hospitalValue ? info.hospitalValue : '',
          "hosValueSource": info.hosValueSource ? info.hosValueSource : '',
          "id": info.id ? info.id : ''
        }
        this.$Http
          .post("etlIndiDataCheckModel/update", param)
          .then(response => {
            if (response.data.response.code == "1") {
              this.$message.success('编辑成功~')
              this.setShowEditInit()
              this.getData()
            } else {
              if (response.data.response.msg) {
                this.$message.error(response.data.response.msg)
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      },
    }
  };
</script>

<style scoped lang="scss">
  .data-detail {
    padding: 10px;
    box-sizing: border-box;

    .date-picker-demo {
      width: 40%;
      display: inline-block;

      .w-date-editor {
        margin: 0 10px;
      }

      .range-separator {
        display: inline-block;
        line-height: 32px;
        vertical-align: middle;
        font-size: 14px;
      }
    }

    .right-value {
      width: 20%;
    }

    .table {
      margin-top: 20px;
    }

    .content-container {
      width: 945px;
      padding: 20px;
      box-sizing: border-box;
    }

    .button-wrap {
      margin-top: 20px;
      text-align: right;
    }
  }
</style>
